package com.ojoin.trade.common.web.controller;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.web.domain.NotificationTemplate;
import com.ojoin.trade.common.web.domain.Pair;
import com.ojoin.trade.common.web.domain.Result;
import com.ojoin.trade.common.web.service.impl.NotificationTemplateService;

@Controller
@RequestMapping(value = "/admin/notificationTemplate")
public class NotificationTemplateController extends SimpleBaseController  {
 
	@Autowired
	private NotificationTemplateService  notificationTemplateService;
	
	
	@RequestMapping(value ="list", method = RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Result list(NotificationTemplate tpl, Pageable page) {
        return new Result(Result.Status.OK,notificationTemplateService.queryList(tpl, page));
	}

	@ResponseBody
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public Result save(NotificationTemplate tpl) {
		List<Pair> validBean=CommonUtils.beanValid(tpl);
		if(CollectionUtils.isNotEmpty(validBean)){
    		return new Result(Result.Status.ERROR, validBean);
    	}
		notificationTemplateService.save(tpl);
		return new Result(Result.Status.OK, "保存模板'" + tpl.getName() + "'成功");
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/{id}/delete", method = RequestMethod.POST,produces=MediaType.APPLICATION_JSON_VALUE)
	public Result delete(@PathVariable("id") Integer id ) {
		NotificationTemplate tpl =notificationTemplateService.queryById(id.intValue());
		if(null==tpl){
			return new Result(Result.Status.ERROR, "模板不存在");
		}
		tpl.markDeleted();
		notificationTemplateService.updateById(tpl);
		return new Result(Result.Status.OK, "删除模板成功");
	}
	 
    

    /**
     * 验证返回格式
     *
     */
	@ResponseBody
    @RequestMapping(value = "validate", method = RequestMethod.POST,produces=MediaType.APPLICATION_JSON_VALUE)
    public String validate(@RequestParam String templateName, @RequestParam(required=false) Integer id) {
            NotificationTemplate template = notificationTemplateService.findByName(templateName);
            if (template == null || (template.getId().equals(id) && template.getName().equals(templateName))) {
            	return Boolean.toString(true);
            } else {
            	return Boolean.toString(false);
            }
    }


}
